<?php

/**
 * IP
 * @author user
 *
 */
class Ip
{
    static public function get()
    {
        $_ip = '0.0.0.0';
        if ($_SERVER) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $_ip = $_SERVER["HTTP_CLIENT_IP"];
            } else if (isset($_SERVER["REMOTE_ADDR"])) {
                $_ip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $_ip = getenv('HTTP_X_FORWARDED_FOR');
            } else if (getenv('HTTP_CLIENT_IP')) {
                $_ip = getenv('HTTP_CLIENT_IP');
            } else if (getenv('REMOTE_ADDR')) {
                $_ip = getenv('REMOTE_ADDR');
            }
        }
        if (!self::is_ip($_ip)) $_ip = '0.0.0.0';
        return $_ip;
    }

    static function is_ip($gonten)
    {
        $ip = explode(".", $gonten);
        for ($i = 0; $i < count($ip); $i++) {
            if ($ip[$i] > 255) {
                return false;
            }
        }
        return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $gonten);
    }

    /**
     * 使用sina接口
     */
    public static function get_area($ip = null)
    {

        // ip为空时使用请求ip
        if (empty($ip)) {
            $ip = self::get();
        }

        $api = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';
        $requestUrl = $api . $ip;

        // 发送http请求
        $content = file_get_contents($requestUrl);

        // 请求错误
        if ($content['info']['http_code'] != 200) {
            return '未知';
        }

        $content = json_decode($content['content'], true);
        $result = (isset($content['province']) ? $content['province'] : '') . ' ' . (isset($content['city']) ? $content['city'] : '');

        return $result;
    }
}